// 盘点页面

import React, {Component} from 'react';
import {DeviceEventEmitter, StatusBar, Text, View, Image, TouchableWithoutFeedback, TouchableNativeFeedback, ScrollView, TouchableOpacity, StyleSheet, TextInput, FlatList} from 'react-native';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import storeActions from '../../../store/actions/store';
import {bindActionCreators} from 'redux';
import {is, fen_to_yuan, fen_money, getNowFormatDate} from '../../../utils';
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import CXIcon from '../../../style/icon/CXIcon';
import ModalDropdown from 'react-native-modal-dropdown';
import Tips from "react-native-root-tips";
import Modal from 'react-native-modalbox';

class inventoryPage extends Component{
    constructor(props){
        super(props);
        this.stockPage = 1;
        this.state = {
            isLoadMore:false,
            activeIndex:0,
            searchVal:'',
            currentGoodsList: [],
            meta: {
                store_nums: '',
                purchaseAmount: ''
            },
            store_nums: 0,
            note: '',
            pagesTitle: '',
            planList: [],
            currentPlan: '',
            searchGoods: [] // 搜索到的商品列表
        };
        this.currentType = 'inventory';
    }
    componentDidMount(){
        let {title, storeAction} = this.props;
        this.setState({
            pagesTitle: title
        });
        storage.load({
            key: `goods-${this.currentType}`
        }).then(res => {
            console.log('这个是缓存的数据', res);
            if (res && res.list) {
                this.setState({
                    currentGoodsList: res.list,
                    store_nums: res.num
                });
            }
        }).catch(err => {

        });

        storeAction.getInventoryPlanList(res => {
            if (res && res.status) {
                if (res.data && res.data.plans && res.data.plans.length) {
                    this.setState({
                        planList: res.data.plans,
                        currentPlan: res.data.plans[0]
                    })
                }

            }
        })
    }
    //创建空布局
    _createEmptyView(){
        return (
            <View style={{height:'100%', alignItems:'center', justifyContent:'center',paddingVertical: 20}}>
                <Text style={{fontSize:16}}>
                    暂无列表数据!!!
                </Text>
            </View>
        );
    }
    // 搜索商品列表渲染
    _renderSearchRow(rowData, index) {
        return (
            <View style={style.goodsItemBox}>
                <TouchableWithoutFeedback onPress={() => this._addGoods(rowData, rowData.store_nums)}>
                    <View style={[style.goodsItem]}>
                        <Text style={style.goodsNo}>
                            {rowData.goods.goods_no}
                        </Text>
                        <Text style={style.goodsNames}>
                            {rowData.goods.name}
                        </Text>
                        <Text style={[style.goodsNames, style.bigSizeType]}>
                            {rowData.colorName} {rowData.sizeName}
                        </Text>
                        <View style={style.goodsNum}>
                            <Text style={{flex: 1}}>
                                ￥ {rowData.goods.market_price}
                            </Text>
                            <Text>
                                库存： {rowData.currentStock}
                            </Text>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        )
    }
    _storageGoods() {
        storage.save({
            key: `goods-${this.currentType}`,
            data: {
                list: this.state.currentGoodsList,
                num: this.state.store_nums
            }
        })
    }
    _searchStock(){
        let {storeAction} = this.props;
        let currentGoodsList = this.state.currentGoodsList;
        if (!this.state.currentPlan) {
            Tips.showFail('请先选择方案');
            return
        }
        if (currentGoodsList.length > 150) {
            Tips.showFail('添加数据不能超过150条');
            return
        }
        storeAction.getInputInventoryData(this.state.searchVal,this.state.currentPlan.id, res => {
            console.log('这个是返回的', res);
            if (res && res.status && res.data) {
                this.setState({
                    searchGoods: res.data
                });
                this.refs.searchModal.open();
            } else {
                this.refs.searchModal.close();
            }
            return;
            if (res && res.status) {
                if (res.data) {
                    let is_new = true;
                    res.data.quantity = 1;
                    currentGoodsList.forEach(item => {
                        if (item.id == res.data.id) {
                            item.quantity = Number(item.quantity) + 1;
                            is_new = false
                        }
                    });
                    if (is_new) {
                        currentGoodsList.push(res.data);
                    }
                    this.setState({
                        currentGoodsList: currentGoodsList
                    }, () => {
                        this._numStore()
                    })
                }
                this.setState({
                    meta: res.meta
                })

            }
        });
    }
    _shopNode(option, index, isSelected) {
        return (
            <Text style={{padding: 5, width: 120}}>
                {option.name}
            </Text>
        );
    }
    _shopTextNode(option) {
        return option.name;
    }
    _selectShop(index, item, type) {
        if (item) {
            this.setState({
                currentPlan: item
            })
        }
    }
    _onSubmitEditing(nativeEvent) {
        console.log('这个是数据', nativeEvent);
        let {storeAction} = this.props;
        let currentGoodsList = this.state.currentGoodsList;
        if (!this.state.currentPlan) {
            Tips.showFail('请先选择方案');
            return
        }
        if (currentGoodsList.length > 150) {
            Tips.showFail('添加数据不能超过150条');
            return
        }
        storeAction.getInventoryData(nativeEvent.text, this.state.currentPlan.id, (res) => {
            console.log('这个是返回的数据呀', res);
            this.setState({
                searchVal: ''
            });
            if (res && res.status) {
                if (res.data) {
                    let is_new = true;
                    res.data.quantity = 1;
                    currentGoodsList.forEach(item => {
                        if (item.id == res.data.id) {
                            item.quantity = Number(item.quantity) + 1;
                            is_new = false
                        }
                    });
                    if (is_new) {
                        currentGoodsList.push(res.data);
                    }
                    this.setState({
                        currentGoodsList: currentGoodsList
                    }, () => {
                        this._numStore()
                    })
                }
            }
        });
    }
    // 改变数量
    _changeListNum(text, index) {
        const list = this.state.currentGoodsList;
        if (is.number(text)) {
            list[index].quantity = text;
            this.setState({
                currentGoodsList: list
            }, () => {
                this._numStore();
            });
        }
    }
    // 删除数组
    _deleteListItem(index) {
        const list = this.state.currentGoodsList;
        list.splice(index, 1);
        this.setState({
            currentGoodsList: list,
        }, () => {
            this._numStore()
        });
    }
    // 计算数量
    _numStore() {
        const list = this.state.currentGoodsList;
        let store_nums = 0;

        list.forEach(item => {
            store_nums += Number(item.quantity)
        })
        this.setState({
            store_nums: store_nums
        }, () => {
            this._storageGoods();
        })
    }
    // 历史记录
    _historyBtn() {
        Actions.push('InventoryHistoryPage')
    }
    // 提交
    _submitStock() {
        let {storeAction} = this.props;
        const list = this.state.currentGoodsList;
        let submitList = [];
        if (list.length) {
            list.forEach(item => {
                let items = {};
                items.goods_name = item.goods.name;
                items.goods_no = item.goods.goods_no;
                items.goods_id = item.goods.id;
                items.currentSku = item.sku;
                items.color = item.colorName;
                items.color_id = item.colorId;
                items.size = item.sizeName;
                items.size_id = item.sizeId;
                items.quantity = item.quantity;
                items.price = item.goods.factory_price;
                items.beforeNumber = item.currentStock;
                submitList.push(items)
            });
            storeAction.confirmInventoryData(submitList, this.state.currentPlan.id, this.state.note, (res) => {
                if (res && res.status) {
                    this.setState({
                        currentGoodsList: [],
                        store_nums: 0
                    });
                    Tips.showSuccess('盘点成功');
                    storage.remove({
                        key: `goods-${this.currentType}`
                    });
                }
            });
            console.log('这个是重组后的数据', submitList);
        } else {
            Tips.showFail('请先添加商品数据');
        }
    }
    //渲染库存列表
    _renderStockList(rowData,index){
        return(
            <TouchableNativeFeedback>
                <View style={style.listItem}>
                    <Text style={[style.listItemText]}>
                        {rowData.goods.goods_no}
                    </Text>
                    <Text style={[style.listItemText]}>
                        {rowData.goods.name}
                    </Text>
                    <Text style={[style.listItemText]}>
                        {rowData.colorName} {rowData.sizeName}
                    </Text>
                    <Text style={[style.listItemText]}>
                        ¥ {rowData.goods.market_price}
                    </Text>
                    <View style={[style.listItemText]}>
                        <View style={style.tableInput}>
                            <TouchableOpacity
                                onPress={() => this._changeListNum(String(Number(this.state.currentGoodsList[index].quantity) - 1), index)}
                            >
                                <Text style={[style.inputCut, {textAlign: 'center', fontSize: 20}]}>
                                    一
                                </Text>
                            </TouchableOpacity>
                            <TextInput style={style.textInput}
                                       keyboardType='numeric'
                                       onChangeText={(text) => this._changeListNum(text, index)}
                                       value={String(rowData.quantity)}
                            >
                            </TextInput>
                            <TouchableOpacity
                                onPress={() => this._changeListNum(String(Number(this.state.currentGoodsList[index].quantity) + 1), index)}

                            >
                                <Text style={[style.inputAdd, {textAlign: 'center', fontSize: 20}]}>
                                    +
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={[style.listItemText, {alignItems: 'center'}]}>
                        <TouchableOpacity
                            style={{width: '100%',alignItems: 'center'}}
                            onPress={() => this._deleteListItem(index)}
                        >
                            <Text style={style.inputDelete}>
                                一
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </TouchableNativeFeedback>
        )
    }
    _closeSearchModal() {
        this.refs.searchModal.close();
    }
    _clearSearchText() {
        this.setState({
            searchVal: ''
        })
    }
    _addGoods(goods) {
        let {storeAction} = this.props;
        let currentGoodsList = this.state.currentGoodsList;
        if (currentGoodsList.length > 150) {
            Tips.showFail('添加数据不能超过150条');
            return
        }
        let is_new = true;
        goods.quantity = 1;
        currentGoodsList.forEach(item => {
            if (item.id == goods.id) {
                item.quantity = Number(item.quantity) + 1;
                is_new = false
            }
        });
        if (is_new) {
            currentGoodsList.push(goods);
        }
        this.setState({
            currentGoodsList: currentGoodsList
        }, () => {
            this._numStore()
        })
    }
    render() {
        let{storeState} = this.props;
        return (
            <View>
                <StatusBar hidden={true}/>

                <View style={style.search}>
                    <View style={style.selectBox}>
                        <View style={style.dropDownBox}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentPlan ? this.state.currentPlan.name : '请选择方案'} options={this.state.planList} renderRow={(option, index, isSelected) => this._shopNode(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentShop')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <TextInput
                            style={style.searchInput}
                            blurOnSubmit={false}
                            onChangeText={(searchVal) => this.setState({searchVal})}
                            onSubmitEditing={({nativeEvent}) => this._onSubmitEditing(nativeEvent)}
                            value={this.state.searchVal}
                        />
                        <TouchableWithoutFeedback onPress={() => {this._searchStock()}}>
                            <View>
                                <Text style={[style.searchText, {marginRight: 10}]}>搜索</Text>
                            </View>
                        </TouchableWithoutFeedback>

                        <Text style={{paddingLeft: 10}}>备注：</Text>

                        <TextInput
                            style={style.searchInput}
                            onChangeText={(note) => this.setState({note})}
                            value={this.state.note}
                        />


                        <View style={{marginLeft: 20}}>
                            <Text>
                                库存总数：{this.state.store_nums}
                            </Text>
                        </View>
                    </View>
                    <View>
                        <Text style={style.searchText} onPress={() =>this._submitStock()}>
                            提交
                        </Text>
                    </View>
                    <View>
                        <Text style={style.historyText} onPress={() =>this._historyBtn()}>
                            历史记录
                        </Text>
                    </View>
                </View>
                <View style={style.list}>
                    <View style={style.listItem}>
                        <Text style={[style.listItemText, style.titleColor]}>
                            货号
                        </Text>
                        <Text style={[style.listItemText, style.titleColor]}>
                            品名
                        </Text>
                        <Text style={[style.listItemText, style.titleColor]}>
                            规格
                        </Text>
                        <Text style={[style.listItemText, style.titleColor]}>
                            吊牌价
                        </Text>
                        <Text style={[style.listItemText, style.titleColor, {textAlign: 'center'}]}>
                            数量
                        </Text>
                        <Text style={[style.listItemText, style.titleColor, {textAlign: 'center'}]}>
                            删除
                        </Text>
                    </View>
                    <View>
                        <FlatList
                            style={{height: 500}}
                            keyExtractor={(item, index) => index.toString()}
                            data={this.state.currentGoodsList}
                            renderItem={({item,index}) => this._renderStockList(item,index)}
                            onEndReachedThreshold={0.1}
                            extraData={this.state}
                            ListEmptyComponent={this._createEmptyView}
                        >
                        </FlatList>
                    </View>

                </View>
                {/*搜索结果弹窗*/}
                <View>
                    <Modal
                        ref={"searchModal"}
                        position="center"
                        style={{backgroundColor:'transparent', width: 900, justifyContent:'center'}}
                        coverScreen={true}
                        swipeArea={280}
                        // backdropPressToClose={false}
                        swipeToClose={false}
                    >
                        <View style={style.searchModalBox}>
                            <View style={style.searchTitle}>
                                <Text>
                                    搜索结果
                                </Text>
                                <View style={[style.closeIcon, {right: 0, top: 0}]}>
                                    <TouchableWithoutFeedback onPress={() => this._closeSearchModal()}>
                                        <View>
                                            <CXIcon name='guanbi' color='#909090' size={30}>

                                            </CXIcon>
                                        </View>
                                    </TouchableWithoutFeedback>
                                </View>
                            </View>
                            <View style={style.searchInputBox}>
                                <View style={{flex: 1}}>
                                    <TextInput
                                        style={style.searchInputs}
                                        onChangeText={(text) => this.setState({searchVal: text})}
                                        value={this.state.searchVal}
                                    >

                                    </TextInput>
                                </View>
                                <View style={[style.closeIcon, {right: 160, top: 28}]}>
                                    <TouchableWithoutFeedback onPress={() => this._clearSearchText()}>
                                        <View>
                                            <CXIcon name='guanbi' color='#909090' size={30}>

                                            </CXIcon>
                                        </View>
                                    </TouchableWithoutFeedback>
                                </View>
                                <Text style={[style.searchBtn, style.textWhite]} onPress={() => this._searchStock()}>
                                    搜索
                                </Text>
                            </View>
                            <View style={style.searchGoods}>

                                <FlatList
                                    style={style.searchScrollView}
                                    numColumns={3}
                                    columnWrapperStyle={{flexDirection: 'row'}}
                                    extraData={this.state.searchGoods}
                                    keyExtractor={(item, index) => index.toString()}
                                    data={this.state.searchGoods}
                                    renderItem={({item, index}) => this._renderSearchRow(item, index)}
                                >

                                </FlatList>
                            </View>
                        </View>
                    </Modal>
                </View>
            </View>
        )
    }
}

const style = StyleSheet.create({
    search: {
        height: '13%',
        paddingHorizontal: 30,
        flexDirection: 'row',
        alignItems: 'center',
    },
    selectBox: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    searchInput: {
        width: 320,
        backgroundColor: white,
        paddingHorizontal: 10,
        height: 44,

    },
    searchText: {
        width: 70,
        textAlign: 'center',
        lineHeight: 44,
        backgroundColor: mainBackgroundColor,
        color: white
    },
    historyText: {
        width: 90,
        textAlign: 'center',
        lineHeight: 44,
        backgroundColor: '#4B8AF2',
        color: white,
        marginLeft: 40
    },
    list: {
        height: '87%',
        backgroundColor: white,
        paddingHorizontal: 30
    },
    listItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        borderBottomWidth: 1,
        borderColor: '#F0F0F5'
    },
    listItemText: {
        flex: 2,
        fontSize: 14,
        color: '#4A4A4A'
    },
    titleColor: {
        color: '#909090'
    },
    flex1: {
        flex: 1
    },
    itemRight: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    dropDown: {
        // width: 120,
        paddingRight: 12,
        color: '#333333'
    },

    dropDownBox: {
        width: 180,
        // backgroundColor: '#F3F3F3',
        height: 44,
        // width: 100,
        // borderRadius: 4,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // padding: 12,
        marginRight: 15,
       /* borderRightWidth: 1,*/
        borderColor: '#D8D8D8',
    },
    tableInput: {
        height: 30,
        borderWidth: 1,
        borderColor: '#D7D7D7',
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 1,
    },
    inputAdd: {
        height: 30,
        lineHeight: 30,
        width: 30,
        borderLeftWidth: 1,
        borderLeftColor: '#D7D7D7',

    },
    textInput: {
        textAlign: 'center',
        height: 50,
        flex: 1,
        color: '#4A4A4A',
    },
    inputCut: {
        height: 30,
        lineHeight: 30,
        width: 30,
        borderRightWidth: 1,
        borderRightColor: '#D7D7D7'
    },
    inputDelete: {
        width: 20,
        height: 20,
        lineHeight: 20,
        backgroundColor: mainBackgroundColor,
        color: white,
        borderRadius: 20,
        textAlign: 'center',
        marginVertical: 10
    },
    // 搜索弹窗部分
    searchModalBox: {

        /* position: 'absolute',
         top: 0,
         width: 900,
         flex: 1,*/
        // alignItems: 'center',
        backgroundColor: white,
        borderRadius: 4
    },
    searchTitle: {
        height: 60,
        justifyContent: 'center',
        paddingLeft: 30,
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8'
    },
    searchInputBox: {
        paddingHorizontal: 30,
        paddingVertical: 20,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8',

    },
    searchBtn: {
        width: 120,
        height: 45,
        textAlign: 'center',
        lineHeight: 45,
        backgroundColor: mainBackgroundColor,
        borderTopRightRadius: 4,
        borderBottomRightRadius: 4
    },
    searchInputs: {
        paddingLeft: 15,
        height: 45,
        backgroundColor: '#F3F3F3',
        borderTopLeftRadius: 4,
        borderBottomLeftRadius: 4
    },
    searchGoods: {
        paddingVertical: 30,
        paddingHorizontal: 10,
        // height: 280,

    },
    searchScrollView: {
        height: 280,
    },
    closeIcon: {
        position: 'absolute',
        right: -30,
        top: -30,

    },
    goodsItemBox: {
        width: '33%',
        marginBottom: 20,
        paddingHorizontal: 10
    },
    goodsItem: {
        padding: 10,
        backgroundColor: '#F3F3F3',
        borderWidth: 1,
        borderColor: '#D7D7D7',
        borderRadius: 4,
    },
    dashed: {
        borderStyle: 'dashed'
    },
    goodsNo: {
        fontSize: 16,
        color: '#4A4A4A',
        fontWeight: 'bold'
    },
    goodsNames: {
        fontSize: 12,
        color: '#4A4A4A',
        marginTop: 5
    },
    bigSizeType: {
        fontSize: 14,
        fontWeight: 'bold',
        color: mainBackgroundColor
    },
    goodsNum: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 5
    },
});

export default connect(state =>({
    storeState: state.store
}),dispatch =>({
    storeAction: bindActionCreators(storeActions,dispatch)
}))(inventoryPage);
